using System;
using System.IO;
using System.Reflection;
using BuildBox.Core.Server;
using BuildBox.Core.Server.Adapters;

namespace BuildBox.Core.Extensions
{
    public static class ResponseExtensions
    {
        public static void ServerBusy(this IHttpListenerResponseAdapter response)
        {
            response.StatusCode = 503;
            response.StatusDescription = "Server was too busy.";
        }

        public static void SetNotFoundStatus(this IHttpListenerResponseAdapter response)
        {
            response.StatusCode = 404;
            response.StatusDescription = "Not Found";
            response.WriteFile("NotFound.htm", ContentType.TextHtml);
        }

        public static void SetServerErrorStatus(this IHttpListenerResponseAdapter response, string message)
        {
            response.StatusCode = 404;
            response.StatusDescription = "Not Found";
            response.WriteFile("NotFound.htm", ContentType.TextHtml);
        }

        public static void Write(this IHttpListenerResponseAdapter response, string value, string contentType)
        {
            var streamWriter = new StreamWriter(response.OutputStream);
            streamWriter.Write(value);
            streamWriter.Flush();
        }

        public static void WriteFile(this IHttpListenerResponseAdapter response, string fileName, string contentType)
        {
            var filePath = Path.Combine(response.Configuration.WebDirectory, fileName);
            if (!File.Exists(filePath))
            {
                response.SetNotFoundStatus();
                return;
            }

            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            byte[] bytes = fs.ReadData();
            fs.Close();

            response.ContentLength64 = bytes.Length;
            response.ContentType = contentType;
            response.OutputStream.Write(bytes, 0, bytes.Length);
            response.OutputStream.Flush();
        }
    }
}